<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlhacktips - Tips for Perl core C code hacking - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlhacktips">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlhacktips.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlhacktips">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlhacktips">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlhacktips">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlhacktips">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlhacktips">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlhacktips">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlhacktips">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlhacktips">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlhacktips">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlhacktips">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlhacktips">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlhacktips">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlhacktips">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlhacktips">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlhacktips">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlhacktips">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlhacktips">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlhacktips">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlhacktips">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlhacktips">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlhacktips">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlhacktips">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlhacktips">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlhacktips">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlhacktips">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlhacktips">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlhacktips">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlhacktips">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlhacktips">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlhacktips">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlhacktips">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlhacktips">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlhacktips">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlhacktips">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlhacktips">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlhacktips">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlhacktips">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlhacktips">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlhacktips">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlhacktips">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlhacktips">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlhacktips">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlhacktips">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlhacktips">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlhacktips">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlhacktips">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlhacktips">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlhacktips">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlhacktips">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlhacktips">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlhacktips">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlhacktips">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlhacktips">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlhacktips">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlhacktips">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlhacktips">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlhacktips">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlhacktips">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlhacktips">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlhacktips">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlhacktips">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlhacktips">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlhacktips">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlhacktips">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlhacktips">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlhacktips">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlhacktips">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlhacktips">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlhacktips">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlhacktips">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlhacktips">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlhacktips">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlhacktips">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlhacktips">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlhacktips">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlhacktips">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlhacktips">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlhacktips">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlhacktips">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlhacktips">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlhacktips.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlhacktips">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlhacktips">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlhacktips">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlhacktips">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlhacktips">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlhacktips">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlhacktips">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlhacktips">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlhacktips">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlhacktips">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlhacktips">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlhacktips">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlhacktips">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlhacktips">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlhacktips">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlhacktips">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlhacktips">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlhacktips">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlhacktips">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlhacktips">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlhacktips">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlhacktips">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlhacktips">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlhacktips">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlhacktips">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlhacktips">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlhacktips">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlhacktips">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlhacktips">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlhacktips">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlhacktips">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlhacktips">5.35.1</a>
          <a class="dropdown-item active" href="perlhacktips.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlhacktips.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlhacktips.html">perlhacktips</a>
          <div id="more">
            (<a href="perlhacktips.txt">source</a>,
            <a href="https://metacpan.org/pod/perlhacktips">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#COMMON-PROBLEMS">COMMON PROBLEMS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Perl-environment-problems">Perl environment problems</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Portability-problems">Portability problems</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Problematic-System-Interfaces">Problematic System Interfaces</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Security-problems">Security problems</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#DEBUGGING">DEBUGGING</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Poking-at-Perl">Poking at Perl</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Using-a-source-level-debugger">Using a source-level debugger</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#gdb-macro-support">gdb macro support</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Dumping-Perl-Data-Structures">Dumping Perl Data Structures</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Using-gdb-to-look-at-specific-parts-of-a-program">Using gdb to look at specific parts of a program</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Using-gdb-to-look-at-what-the-parser/lexer-are-doing">Using gdb to look at what the parser/lexer are doing</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#SOURCE-CODE-STATIC-ANALYSIS">SOURCE CODE STATIC ANALYSIS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#lint">lint</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Coverity">Coverity</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#HP-UX-cadvise-(Code-Advisor)">HP-UX cadvise (Code Advisor)</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#cpd-(cut-and-paste-detector)">cpd (cut-and-paste detector)</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#gcc-warnings">gcc warnings</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Warnings-of-other-C-compilers">Warnings of other C compilers</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#MEMORY-DEBUGGERS">MEMORY DEBUGGERS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#valgrind">valgrind</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#AddressSanitizer">AddressSanitizer</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#PROFILING">PROFILING</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Gprof-Profiling">Gprof Profiling</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#GCC-gcov-Profiling">GCC gcov Profiling</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#MISCELLANEOUS-TRICKS">MISCELLANEOUS TRICKS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#PERL_DESTRUCT_LEVEL">PERL_DESTRUCT_LEVEL</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#PERL_MEM_LOG">PERL_MEM_LOG</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#DDD-over-gdb">DDD over gdb</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#C-backtrace">C backtrace</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Poison">Poison</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#Read-only-optrees">Read-only optrees</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#When-is-a-bool-not-a-bool?">When is a bool not a bool?</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#The-.i-Targets">The .i Targets</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlhacktips.html#AUTHOR">AUTHOR</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlhacktips.html#NAME">#</a>NAME</h1>

<p>perlhacktips - Tips for Perl core C code hacking</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlhacktips.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This document will help you learn the best way to go about hacking on the Perl core C code. It covers common problems, debugging, profiling, and more.</p>

<p>If you haven&#39;t read <a href="perlhack.html">perlhack</a> and <a href="perlhacktut.html">perlhacktut</a> yet, you might want to do that first.</p>

<h1 id="COMMON-PROBLEMS"><a class="permalink" href="perlhacktips.html#COMMON-PROBLEMS">#</a><a id="COMMON"></a>COMMON PROBLEMS</h1>

<p>Perl source plays by ANSI C89 rules: no C99 (or C++) extensions. You don&#39;t care about some particular platform having broken Perl? I hear there is still a strong demand for J2EE programmers.</p>

<h2 id="Perl-environment-problems"><a class="permalink" href="perlhacktips.html#Perl-environment-problems">#</a><a id="Perl"></a>Perl environment problems</h2>

<ul>

<li><p>Not compiling with threading</p>

<p>Compiling with threading (-Duseithreads) completely rewrites the function prototypes of Perl. You better try your changes with that. Related to this is the difference between &quot;Perl_-less&quot; and &quot;Perl_-ly&quot; APIs, for example:</p>

<pre><code>Perl_sv_setiv(aTHX_ ...);
sv_setiv(...);</code></pre>

<p>The first one explicitly passes in the context, which is needed for e.g. threaded builds. The second one does that implicitly; do not get them mixed. If you are not passing in a aTHX_, you will need to do a dTHX as the first thing in the function.</p>

<p>See <a href="perlguts.html#How-multiple-interpreters-and-concurrency-are-supported">&quot;How multiple interpreters and concurrency are supported&quot; in perlguts</a> for further discussion about context.</p>

</li>
<li><p>Not compiling with -DDEBUGGING</p>

<p>The DEBUGGING define exposes more code to the compiler, therefore more ways for things to go wrong. You should try it.</p>

</li>
<li><p>Introducing (non-read-only) globals</p>

<p>Do not introduce any modifiable globals, truly global or file static. They are bad form and complicate multithreading and other forms of concurrency. The right way is to introduce them as new interpreter variables, see <i>intrpvar.h</i> (at the very end for binary compatibility).</p>

<p>Introducing read-only (const) globals is okay, as long as you verify with e.g. <code>nm libperl.a|egrep -v &#39; [TURtr] &#39;</code> (if your <code>nm</code> has BSD-style output) that the data you added really is read-only. (If it is, it shouldn&#39;t show up in the output of that command.)</p>

<p>If you want to have static strings, make them constant:</p>

<pre><code>static const char etc[] = &quot;...&quot;;</code></pre>

<p>If you want to have arrays of constant strings, note carefully the right combination of <code>const</code>s:</p>

<pre><code>static const char * const yippee[] =
    {&quot;hi&quot;, &quot;ho&quot;, &quot;silver&quot;};</code></pre>

</li>
<li><p>Not exporting your new function</p>

<p>Some platforms (Win32, AIX, VMS, OS/2, to name a few) require any function that is part of the public API (the shared Perl library) to be explicitly marked as exported. See the discussion about <i>embed.pl</i> in <a href="perlguts.html">perlguts</a>.</p>

</li>
<li><p>Exporting your new function</p>

<p>The new shiny result of either genuine new functionality or your arduous refactoring is now ready and correctly exported. So what could possibly go wrong?</p>

<p>Maybe simply that your function did not need to be exported in the first place. Perl has a long and not so glorious history of exporting functions that it should not have.</p>

<p>If the function is used only inside one source code file, make it static. See the discussion about <i>embed.pl</i> in <a href="perlguts.html">perlguts</a>.</p>

<p>If the function is used across several files, but intended only for Perl&#39;s internal use (and this should be the common case), do not export it to the public API. See the discussion about <i>embed.pl</i> in <a href="perlguts.html">perlguts</a>.</p>

</li>
</ul>

<h2 id="Portability-problems"><a class="permalink" href="perlhacktips.html#Portability-problems">#</a><a id="Portability"></a>Portability problems</h2>

<p>The following are common causes of compilation and/or execution failures, not common to Perl as such. The C FAQ is good bedtime reading. Please test your changes with as many C compilers and platforms as possible; we will, anyway, and it&#39;s nice to save oneself from public embarrassment.</p>

<p>If using gcc, you can add the <code>-std=c89</code> option which will hopefully catch most of these unportabilities. (However it might also catch incompatibilities in your system&#39;s header files.)</p>

<p>Use the Configure <code>-Dgccansipedantic</code> flag to enable the gcc <code>-ansi -pedantic</code> flags which enforce stricter ANSI rules.</p>

<p>If using the <code>gcc -Wall</code> note that not all the possible warnings (like <code>-Wuninitialized</code>) are given unless you also compile with <code>-O</code>.</p>

<p>Note that if using gcc, starting from Perl 5.9.5 the Perl core source code files (the ones at the top level of the source code distribution, but not e.g. the extensions under ext/) are automatically compiled with as many as possible of the <code>-std=c89</code>, <code>-ansi</code>, <code>-pedantic</code>, and a selection of <code>-W</code> flags (see cflags.SH).</p>

<p>Also study <a href="perlport.html">perlport</a> carefully to avoid any bad assumptions about the operating system, filesystems, character set, and so forth.</p>

<p>You may once in a while try a &quot;make microperl&quot; to see whether we can still compile Perl with just the bare minimum of interfaces. (See README.micro.)</p>

<p>Do not assume an operating system indicates a certain compiler.</p>

<ul>

<li><p>Casting pointers to integers or casting integers to pointers</p>

<pre><code>void castaway(U8* p)
{
  IV i = p;</code></pre>

<p>or</p>

<pre><code>void castaway(U8* p)
{
  IV i = (IV)p;</code></pre>

<p>Both are bad, and broken, and unportable. Use the PTR2IV() macro that does it right. (Likewise, there are PTR2UV(), PTR2NV(), INT2PTR(), and NUM2PTR().)</p>

</li>
<li><p>Casting between function pointers and data pointers</p>

<p>Technically speaking casting between function pointers and data pointers is unportable and undefined, but practically speaking it seems to work, but you should use the FPTR2DPTR() and DPTR2FPTR() macros. Sometimes you can also play games with unions.</p>

</li>
<li><p>Assuming sizeof(int) == sizeof(long)</p>

<p>There are platforms where longs are 64 bits, and platforms where ints are 64 bits, and while we are out to shock you, even platforms where shorts are 64 bits. This is all legal according to the C standard. (In other words, &quot;long long&quot; is not a portable way to specify 64 bits, and &quot;long long&quot; is not even guaranteed to be any wider than &quot;long&quot;.)</p>

<p>Instead, use the definitions IV, UV, IVSIZE, I32SIZE, and so forth. Avoid things like I32 because they are <b>not</b> guaranteed to be <i>exactly</i> 32 bits, they are <i>at least</i> 32 bits, nor are they guaranteed to be <b>int</b> or <b>long</b>. If you really explicitly need 64-bit variables, use I64 and U64, but only if guarded by HAS_QUAD.</p>

</li>
<li><p>Assuming one can dereference any type of pointer for any type of data</p>

<pre><code>char *p = ...;
long pony = *(long *)p;    /* BAD */</code></pre>

<p>Many platforms, quite rightly so, will give you a core dump instead of a pony if the p happens not to be correctly aligned.</p>

</li>
<li><p>Lvalue casts</p>

<pre><code class="plaintext">(int)*p = ...;    /* BAD */</code></pre>

<p>Simply not portable. Get your lvalue to be of the right type, or maybe use temporary variables, or dirty tricks with unions.</p>

</li>
<li><p>Assume <b>anything</b> about structs (especially the ones you don&#39;t control, like the ones coming from the system headers)</p>

<ul>

<li><p>That a certain field exists in a struct</p>

</li>
<li><p>That no other fields exist besides the ones you know of</p>

</li>
<li><p>That a field is of certain signedness, sizeof, or type</p>

</li>
<li><p>That the fields are in a certain order</p>

<ul>

<li><p>While C guarantees the ordering specified in the struct definition, between different platforms the definitions might differ</p>

</li>
</ul>

</li>
<li><p>That the sizeof(struct) or the alignments are the same everywhere</p>

<ul>

<li><p>There might be padding bytes between the fields to align the fields - the bytes can be anything</p>

</li>
<li><p>Structs are required to be aligned to the maximum alignment required by the fields - which for native types is for usually equivalent to sizeof() of the field</p>

</li>
</ul>

</li>
</ul>

</li>
<li><p>Assuming the character set is ASCIIish</p>

<p>Perl can compile and run under EBCDIC platforms. See <a href="perlebcdic.html">perlebcdic</a>. This is transparent for the most part, but because the character sets differ, you shouldn&#39;t use numeric (decimal, octal, nor hex) constants to refer to characters. You can safely say <code>&#39;A&#39;</code>, but not <code>0x41</code>. You can safely say <code>&#39;\n&#39;</code>, but not <code>\012</code>. However, you can use macros defined in <i>utf8.h</i> to specify any code point portably. <code>LATIN1_TO_NATIVE(0xDF)</code> is going to be the code point that means LATIN SMALL LETTER SHARP S on whatever platform you are running on (on ASCII platforms it compiles without adding any extra code, so there is zero performance hit on those). The acceptable inputs to <code>LATIN1_TO_NATIVE</code> are from <code>0x00</code> through <code>0xFF</code>. If your input isn&#39;t guaranteed to be in that range, use <code>UNICODE_TO_NATIVE</code> instead. <code>NATIVE_TO_LATIN1</code> and <code>NATIVE_TO_UNICODE</code> translate the opposite direction.</p>

<p>If you need the string representation of a character that doesn&#39;t have a mnemonic name in C, you should add it to the list in <i>regen/unicode_constants.pl</i>, and have Perl create <code>#define</code>&#39;s for you, based on the current platform.</p>

<p>Note that the <code>is<i>FOO</i></code> and <code>to<i>FOO</i></code> macros in <i>handy.h</i> work properly on native code points and strings.</p>

<p>Also, the range &#39;A&#39; - &#39;Z&#39; in ASCII is an unbroken sequence of 26 upper case alphabetic characters. That is not true in EBCDIC. Nor for &#39;a&#39; to &#39;z&#39;. But &#39;0&#39; - &#39;9&#39; is an unbroken range in both systems. Don&#39;t assume anything about other ranges. (Note that special handling of ranges in regular expression patterns and transliterations makes it appear to Perl code that the aforementioned ranges are all unbroken.)</p>

<p>Many of the comments in the existing code ignore the possibility of EBCDIC, and may be wrong therefore, even if the code works. This is actually a tribute to the successful transparent insertion of being able to handle EBCDIC without having to change pre-existing code.</p>

<p>UTF-8 and UTF-EBCDIC are two different encodings used to represent Unicode code points as sequences of bytes. Macros with the same names (but different definitions) in <i>utf8.h</i> and <i>utfebcdic.h</i> are used to allow the calling code to think that there is only one such encoding. This is almost always referred to as <code>utf8</code>, but it means the EBCDIC version as well. Again, comments in the code may well be wrong even if the code itself is right. For example, the concept of UTF-8 <code>invariant characters</code> differs between ASCII and EBCDIC. On ASCII platforms, only characters that do not have the high-order bit set (i.e. whose ordinals are strict ASCII, 0 - 127) are invariant, and the documentation and comments in the code may assume that, often referring to something like, say, <code>hibit</code>. The situation differs and is not so simple on EBCDIC machines, but as long as the code itself uses the <code>NATIVE_IS_INVARIANT()</code> macro appropriately, it works, even if the comments are wrong.</p>

<p>As noted in <a href="perlhack.html#TESTING">&quot;TESTING&quot; in perlhack</a>, when writing test scripts, the file <i>t/charset_tools.pl</i> contains some helpful functions for writing tests valid on both ASCII and EBCDIC platforms. Sometimes, though, a test can&#39;t use a function and it&#39;s inconvenient to have different test versions depending on the platform. There are 20 code points that are the same in all 4 character sets currently recognized by Perl (the 3 EBCDIC code pages plus ISO 8859-1 (ASCII/Latin1)). These can be used in such tests, though there is a small possibility that Perl will become available in yet another character set, breaking your test. All but one of these code points are C0 control characters. The most significant controls that are the same are <code>\0</code>, <code>\r</code>, and <code>\N{VT}</code> (also specifiable as <code>\cK</code>, <code>\x0B</code>, <code>\N{U+0B}</code>, or <code>\013</code>). The single non-control is U+00B6 PILCROW SIGN. The controls that are the same have the same bit pattern in all 4 character sets, regardless of the UTF8ness of the string containing them. The bit pattern for U+B6 is the same in all 4 for non-UTF8 strings, but differs in each when its containing string is UTF-8 encoded. The only other code points that have some sort of sameness across all 4 character sets are the pair 0xDC and 0xFC. Together these represent upper- and lowercase LATIN LETTER U WITH DIAERESIS, but which is upper and which is lower may be reversed: 0xDC is the capital in Latin1 and 0xFC is the small letter, while 0xFC is the capital in EBCDIC and 0xDC is the small one. This factoid may be exploited in writing case insensitive tests that are the same across all 4 character sets.</p>

</li>
<li><p>Assuming the character set is just ASCII</p>

<p>ASCII is a 7 bit encoding, but bytes have 8 bits in them. The 128 extra characters have different meanings depending on the locale. Absent a locale, currently these extra characters are generally considered to be unassigned, and this has presented some problems. This has being changed starting in 5.12 so that these characters can be considered to be Latin-1 (ISO-8859-1).</p>

</li>
<li><p>Mixing #define and #ifdef</p>

<pre><code class="plaintext">#define BURGLE(x) ... \
#ifdef BURGLE_OLD_STYLE        /* BAD */
... do it the old way ... \
#else
... do it the new way ... \
#endif</code></pre>

<p>You cannot portably &quot;stack&quot; cpp directives. For example in the above you need two separate BURGLE() #defines, one for each #ifdef branch.</p>

</li>
<li><p>Adding non-comment stuff after #endif or #else</p>

<pre><code class="plaintext">#ifdef SNOSH
...
#else !SNOSH    /* BAD */
...
#endif SNOSH    /* BAD */</code></pre>

<p>The #endif and #else cannot portably have anything non-comment after them. If you want to document what is going (which is a good idea especially if the branches are long), use (C) comments:</p>

<pre><code class="plaintext">#ifdef SNOSH
...
#else /* !SNOSH */
...
#endif /* SNOSH */</code></pre>

<p>The gcc option <code>-Wendif-labels</code> warns about the bad variant (by default on starting from Perl 5.9.4).</p>

</li>
<li><p>Having a comma after the last element of an enum list</p>

<pre><code>enum color {
  CERULEAN,
  CHARTREUSE,
  CINNABAR,     /* BAD */
};</code></pre>

<p>is not portable. Leave out the last comma.</p>

<p>Also note that whether enums are implicitly morphable to ints varies between compilers, you might need to (int).</p>

</li>
<li><p>Using //-comments</p>

<pre><code class="plaintext">// This function bamfoodles the zorklator.   /* BAD */</code></pre>

<p>That is C99 or C++. Perl is C89. Using the //-comments is silently allowed by many C compilers but cranking up the ANSI C89 strictness (which we like to do) causes the compilation to fail.</p>

</li>
<li><p>Mixing declarations and code</p>

<pre><code>void zorklator()
{
  int n = 3;
  set_zorkmids(n);    /* BAD */
  int q = 4;</code></pre>

<p>That is C99 or C++. Some C compilers allow that, but you shouldn&#39;t.</p>

<p>The gcc option <code>-Wdeclaration-after-statement</code> scans for such problems (by default on starting from Perl 5.9.4).</p>

</li>
<li><p>Introducing variables inside for()</p>

<pre><code class="plaintext">for(int i = ...; ...; ...) {    /* BAD */</code></pre>

<p>That is C99 or C++. While it would indeed be awfully nice to have that also in C89, to limit the scope of the loop variable, alas, we cannot.</p>

</li>
<li><p>Mixing signed char pointers with unsigned char pointers</p>

<pre><code class="plaintext">int foo(char *s) { ... }
...
unsigned char *t = ...; /* Or U8* t = ... */
foo(t);   /* BAD */</code></pre>

<p>While this is legal practice, it is certainly dubious, and downright fatal in at least one platform: for example VMS cc considers this a fatal error. One cause for people often making this mistake is that a &quot;naked char&quot; and therefore dereferencing a &quot;naked char pointer&quot; have an undefined signedness: it depends on the compiler and the flags of the compiler and the underlying platform whether the result is signed or unsigned. For this very same reason using a &#39;char&#39; as an array index is bad.</p>

</li>
<li><p>Macros that have string constants and their arguments as substrings of the string constants</p>

<pre><code>#define FOO(n) printf(&quot;number = %d\n&quot;, n)    /* BAD */
FOO(10);</code></pre>

<p>Pre-ANSI semantics for that was equivalent to</p>

<pre><code>printf(&quot;10umber = %d\10&quot;);</code></pre>

<p>which is probably not what you were expecting. Unfortunately at least one reasonably common and modern C compiler does &quot;real backward compatibility&quot; here, in AIX that is what still happens even though the rest of the AIX compiler is very happily C89.</p>

</li>
<li><p>Using printf formats for non-basic C types</p>

<pre><code>IV i = ...;
printf(&quot;i = %d\n&quot;, i);    /* BAD */</code></pre>

<p>While this might by accident work in some platform (where IV happens to be an <code>int</code>), in general it cannot. IV might be something larger. Even worse the situation is with more specific types (defined by Perl&#39;s configuration step in <i>config.h</i>):</p>

<pre><code>Uid_t who = ...;
printf(&quot;who = %d\n&quot;, who);    /* BAD */</code></pre>

<p>The problem here is that Uid_t might be not only not <code>int</code>-wide but it might also be unsigned, in which case large uids would be printed as negative values.</p>

<p>There is no simple solution to this because of printf()&#39;s limited intelligence, but for many types the right format is available as with either &#39;f&#39; or &#39;_f&#39; suffix, for example:</p>

<pre><code>IVdf /* IV in decimal */
UVxf /* UV is hexadecimal */

printf(&quot;i = %&quot;IVdf&quot;\n&quot;, i); /* The IVdf is a string constant. */

Uid_t_f /* Uid_t in decimal */

printf(&quot;who = %&quot;Uid_t_f&quot;\n&quot;, who);</code></pre>

<p>Or you can try casting to a &quot;wide enough&quot; type:</p>

<pre><code>printf(&quot;i = %&quot;IVdf&quot;\n&quot;, (IV)something_very_small_and_signed);</code></pre>

<p>See <a href="perlguts.html#Formatted-Printing-of-Size_t-and-SSize_t">&quot;Formatted Printing of Size_t and SSize_t&quot; in perlguts</a> for how to print those.</p>

<p>Also remember that the <code>%p</code> format really does require a void pointer:</p>

<pre><code>U8* p = ...;
printf(&quot;p = %p\n&quot;, (void*)p);</code></pre>

<p>The gcc option <code>-Wformat</code> scans for such problems.</p>

</li>
<li><p>Blindly using variadic macros</p>

<p>gcc has had them for a while with its own syntax, and C99 brought them with a standardized syntax. Don&#39;t use the former, and use the latter only if the HAS_C99_VARIADIC_MACROS is defined.</p>

</li>
<li><p>Blindly passing va_list</p>

<p>Not all platforms support passing va_list to further varargs (stdarg) functions. The right thing to do is to copy the va_list using the Perl_va_copy() if the NEED_VA_COPY is defined.</p>

</li>
<li><p>Using gcc statement expressions</p>

<pre><code class="plaintext">val = ({...;...;...});    /* BAD */</code></pre>

<p>While a nice extension, it&#39;s not portable. The Perl code does admittedly use them if available to gain some extra speed (essentially as a funky form of inlining), but you shouldn&#39;t.</p>

</li>
<li><p>Binding together several statements in a macro</p>

<p>Use the macros STMT_START and STMT_END.</p>

<pre><code>STMT_START {
   ...
} STMT_END</code></pre>

</li>
<li><p>Testing for operating systems or versions when should be testing for features</p>

<pre><code>#ifdef __FOONIX__    /* BAD */
foo = quux();
#endif</code></pre>

<p>Unless you know with 100% certainty that quux() is only ever available for the &quot;Foonix&quot; operating system <b>and</b> that is available <b>and</b> correctly working for <b>all</b> past, present, <b>and</b> future versions of &quot;Foonix&quot;, the above is very wrong. This is more correct (though still not perfect, because the below is a compile-time check):</p>

<pre><code>#ifdef HAS_QUUX
foo = quux();
#endif</code></pre>

<p>How does the HAS_QUUX become defined where it needs to be? Well, if Foonix happens to be Unixy enough to be able to run the Configure script, and Configure has been taught about detecting and testing quux(), the HAS_QUUX will be correctly defined. In other platforms, the corresponding configuration step will hopefully do the same.</p>

<p>In a pinch, if you cannot wait for Configure to be educated, or if you have a good hunch of where quux() might be available, you can temporarily try the following:</p>

<pre><code>#if (defined(__FOONIX__) || defined(__BARNIX__))
# define HAS_QUUX
#endif

...

#ifdef HAS_QUUX
foo = quux();
#endif</code></pre>

<p>But in any case, try to keep the features and operating systems separate.</p>

<p>A good resource on the predefined macros for various operating systems, compilers, and so forth is <a href="http://sourceforge.net/p/predef/wiki/Home/">http://sourceforge.net/p/predef/wiki/Home/</a></p>

</li>
<li><p>Assuming the contents of static memory pointed to by the return values of Perl wrappers for C library functions doesn&#39;t change. Many C library functions return pointers to static storage that can be overwritten by subsequent calls to the same or related functions. Perl has light-weight wrappers for some of these functions, and which don&#39;t make copies of the static memory. A good example is the interface to the environment variables that are in effect for the program. Perl has <code>PerlEnv_getenv</code> to get values from the environment. But the return is a pointer to static memory in the C library. If you are using the value to immediately test for something, that&#39;s fine, but if you save the value and expect it to be unchanged by later processing, you would be wrong, but perhaps you wouldn&#39;t know it because different C library implementations behave differently, and the one on the platform you&#39;re testing on might work for your situation. But on some platforms, a subsequent call to <code>PerlEnv_getenv</code> or related function WILL overwrite the memory that your first call points to. This has led to some hard-to-debug problems. Do a <a href="perlapi.html#savepv">&quot;savepv&quot; in perlapi</a> to make a copy, thus avoiding these problems. You will have to free the copy when you&#39;re done to avoid memory leaks. If you don&#39;t have control over when it gets freed, you&#39;ll need to make the copy in a mortal scalar, like so:</p>

<pre><code>if ((s = PerlEnv_getenv(&quot;foo&quot;) == NULL) {
   ... /* handle NULL case */
}
else {
    s = SvPVX(sv_2mortal(newSVpv(s, 0)));
}</code></pre>

<p>The above example works only if <code>&quot;s&quot;</code> is <code>NUL</code>-terminated; otherwise you have to pass its length to <code>newSVpv</code>.</p>

</li>
</ul>

<h2 id="Problematic-System-Interfaces"><a class="permalink" href="perlhacktips.html#Problematic-System-Interfaces">#</a><a id="Problematic"></a>Problematic System Interfaces</h2>

<ul>

<li><p>Perl strings are NOT the same as C strings: They may contain <code>NUL</code> characters, whereas a C string is terminated by the first <code>NUL</code>. That is why Perl API functions that deal with strings generally take a pointer to the first byte and either a length or a pointer to the byte just beyond the final one.</p>

<p>And this is the reason that many of the C library string handling functions should not be used. They don&#39;t cope with the full generality of Perl strings. It may be that your test cases don&#39;t have embedded <code>NUL</code>s, and so the tests pass, whereas there may well eventually arise real-world cases where they fail. A lesson here is to include <code>NUL</code>s in your tests. Now it&#39;s fairly rare in most real world cases to get <code>NUL</code>s, so your code may seem to work, until one day a <code>NUL</code> comes along.</p>

<p>Here&#39;s an example. It used to be a common paradigm, for decades, in the perl core to use <span style="white-space: nowrap;"><code>strchr(&quot;list&quot;, c)</code></span> to see if the character <code>c</code> is any of the ones given in <code>&quot;list&quot;</code>, a double-quote-enclosed string of the set of characters that we are seeing if <code>c</code> is one of. As long as <code>c</code> isn&#39;t a <code>NUL</code>, it works. But when <code>c</code> is a <code>NUL</code>, <code>strchr</code> returns a pointer to the terminating <code>NUL</code> in <code>&quot;list&quot;</code>. This likely will result in a segfault or a security issue when the caller uses that end pointer as the starting point to read from.</p>

<p>A solution to this and many similar issues is to use the <code>mem</code><i>-foo</i> C library functions instead. In this case <code>memchr</code> can be used to see if <code>c</code> is in <code>&quot;list&quot;</code> and works even if <code>c</code> is <code>NUL</code>. These functions need an additional parameter to give the string length. In the case of literal string parameters, perl has defined macros that calculate the length for you. See <a href="perlapi.html#String-Handling">&quot;String Handling&quot; in perlapi</a>.</p>

</li>
<li><p>malloc(0), realloc(0), calloc(0, 0) are non-portable. To be portable allocate at least one byte. (In general you should rarely need to work at this low level, but instead use the various malloc wrappers.)</p>

</li>
<li><p>snprintf() - the return type is unportable. Use my_snprintf() instead.</p>

</li>
</ul>

<h2 id="Security-problems"><a class="permalink" href="perlhacktips.html#Security-problems">#</a><a id="Security"></a>Security problems</h2>

<p>Last but not least, here are various tips for safer coding. See also <a href="perlclib.html">perlclib</a> for libc/stdio replacements one should use.</p>

<ul>

<li><p>Do not use gets()</p>

<p>Or we will publicly ridicule you. Seriously.</p>

</li>
<li><p>Do not use tmpfile()</p>

<p>Use mkstemp() instead.</p>

</li>
<li><p>Do not use strcpy() or strcat() or strncpy() or strncat()</p>

<p>Use my_strlcpy() and my_strlcat() instead: they either use the native implementation, or Perl&#39;s own implementation (borrowed from the public domain implementation of INN).</p>

</li>
<li><p>Do not use sprintf() or vsprintf()</p>

<p>If you really want just plain byte strings, use my_snprintf() and my_vsnprintf() instead, which will try to use snprintf() and vsnprintf() if those safer APIs are available. If you want something fancier than a plain byte string, use <a href="perlapi.html#form"><code>Perl_form</code>()</a> or SVs and <a href="perlapi.html#sv_catpvf"><code>Perl_sv_catpvf()</code></a>.</p>

<p>Note that glibc <code>printf()</code>, <code>sprintf()</code>, etc. are buggy before glibc version 2.17. They won&#39;t allow a <code>%.s</code> format with a precision to create a string that isn&#39;t valid UTF-8 if the current underlying locale of the program is UTF-8. What happens is that the <code>%s</code> and its operand are simply skipped without any notice. <a href="https://sourceware.org/bugzilla/show_bug.cgi?id=6530">https://sourceware.org/bugzilla/show_bug.cgi?id=6530</a>.</p>

</li>
<li><p>Do not use atoi()</p>

<p>Use grok_atoUV() instead. atoi() has ill-defined behavior on overflows, and cannot be used for incremental parsing. It is also affected by locale, which is bad.</p>

</li>
<li><p>Do not use strtol() or strtoul()</p>

<p>Use grok_atoUV() instead. strtol() or strtoul() (or their IV/UV-friendly macro disguises, Strtol() and Strtoul(), or Atol() and Atoul() are affected by locale, which is bad.</p>

</li>
</ul>

<h1 id="DEBUGGING"><a class="permalink" href="perlhacktips.html#DEBUGGING">#</a>DEBUGGING</h1>

<p>You can compile a special debugging version of Perl, which allows you to use the <code>-D</code> option of Perl to tell more about what Perl is doing. But sometimes there is no alternative than to dive in with a debugger, either to see the stack trace of a core dump (very useful in a bug report), or trying to figure out what went wrong before the core dump happened, or how did we end up having wrong or unexpected results.</p>

<h2 id="Poking-at-Perl"><a class="permalink" href="perlhacktips.html#Poking-at-Perl">#</a><a id="Poking"></a>Poking at Perl</h2>

<p>To really poke around with Perl, you&#39;ll probably want to build Perl for debugging, like this:</p>

<pre><code class="plaintext">./Configure -d -DDEBUGGING
make</code></pre>

<p><code>-DDEBUGGING</code> turns on the C compiler&#39;s <code>-g</code> flag to have it produce debugging information which will allow us to step through a running program, and to see in which C function we are at (without the debugging information we might see only the numerical addresses of the functions, which is not very helpful). It will also turn on the <code>DEBUGGING</code> compilation symbol which enables all the internal debugging code in Perl. There are a whole bunch of things you can debug with this: <a href="perlrun.html#-Dletters">perlrun</a> lists them all, and the best way to find out about them is to play about with them. The most useful options are probably</p>

<pre><code class="plaintext">l  Context (loop) stack processing
s  Stack snapshots (with v, displays all stacks)
t  Trace execution
o  Method and overloading resolution
c  String/numeric conversions</code></pre>

<p>For example</p>

<pre><code>$ perl -Dst -e &#39;$a + 1&#39;
....
(-e:1)	gvsv(main::a)
    =&gt;  UNDEF
(-e:1)	const(IV(1))
    =&gt;  UNDEF  IV(1)
(-e:1)	add
    =&gt;  NV(1)</code></pre>

<p>Some of the functionality of the debugging code can be achieved with a non-debugging perl by using XS modules:</p>

<pre><code class="plaintext">-Dr =&gt; use re &#39;debug&#39;
-Dx =&gt; use O &#39;Debug&#39;</code></pre>

<h2 id="Using-a-source-level-debugger"><a class="permalink" href="perlhacktips.html#Using-a-source-level-debugger">#</a><a id="Using"></a>Using a source-level debugger</h2>

<p>If the debugging output of <code>-D</code> doesn&#39;t help you, it&#39;s time to step through perl&#39;s execution with a source-level debugger.</p>

<ul>

<li><p>We&#39;ll use <code>gdb</code> for our examples here; the principles will apply to any debugger (many vendors call their debugger <code>dbx</code>), but check the manual of the one you&#39;re using.</p>

</li>
</ul>

<p>To fire up the debugger, type</p>

<pre><code class="plaintext">gdb ./perl</code></pre>

<p>Or if you have a core dump:</p>

<pre><code class="plaintext">gdb ./perl core</code></pre>

<p>You&#39;ll want to do that in your Perl source tree so the debugger can read the source code. You should see the copyright message, followed by the prompt.</p>

<pre><code class="plaintext">(gdb)</code></pre>

<p><code>help</code> will get you into the documentation, but here are the most useful commands:</p>

<ul>

<li><p>run [args]</p>

<p>Run the program with the given arguments.</p>

</li>
<li><p>break function_name</p>

</li>
<li><p>break source.c:xxx</p>

<p>Tells the debugger that we&#39;ll want to pause execution when we reach either the named function (but see <a href="perlguts.html#Internal-Functions">&quot;Internal Functions&quot; in perlguts</a>!) or the given line in the named source file.</p>

</li>
<li><p>step</p>

<p>Steps through the program a line at a time.</p>

</li>
<li><p>next</p>

<p>Steps through the program a line at a time, without descending into functions.</p>

</li>
<li><p>continue</p>

<p>Run until the next breakpoint.</p>

</li>
<li><p>finish</p>

<p>Run until the end of the current function, then stop again.</p>

</li>
<li><p>&#39;enter&#39;</p>

<p>Just pressing Enter will do the most recent operation again - it&#39;s a blessing when stepping through miles of source code.</p>

</li>
<li><p>ptype</p>

<p>Prints the C definition of the argument given.</p>

<pre><code>(gdb) ptype PL_op
type = struct op {
    OP *op_next;
    OP *op_sibparent;
    OP *(*op_ppaddr)(void);
    PADOFFSET op_targ;
    unsigned int op_type : 9;
    unsigned int op_opt : 1;
    unsigned int op_slabbed : 1;
    unsigned int op_savefree : 1;
    unsigned int op_static : 1;
    unsigned int op_folded : 1;
    unsigned int op_spare : 2;
    U8 op_flags;
    U8 op_private;
} *</code></pre>

</li>
<li><p>print</p>

<p>Execute the given C code and print its results. <b>WARNING</b>: Perl makes heavy use of macros, and <i>gdb</i> does not necessarily support macros (see later <a href="perlhacktips.html#gdb-macro-support">&quot;gdb macro support&quot;</a>). You&#39;ll have to substitute them yourself, or to invoke cpp on the source code files (see <a href="perlhacktips.html#The-.i-Targets">&quot;The .i Targets&quot;</a>) So, for instance, you can&#39;t say</p>

<pre><code class="plaintext">print SvPV_nolen(sv)</code></pre>

<p>but you have to say</p>

<pre><code class="plaintext">print Perl_sv_2pv_nolen(sv)</code></pre>

</li>
</ul>

<p>You may find it helpful to have a &quot;macro dictionary&quot;, which you can produce by saying <code>cpp -dM perl.c | sort</code>. Even then, <i>cpp</i> won&#39;t recursively apply those macros for you.</p>

<h2 id="gdb-macro-support"><a class="permalink" href="perlhacktips.html#gdb-macro-support">#</a><a id="gdb"></a>gdb macro support</h2>

<p>Recent versions of <i>gdb</i> have fairly good macro support, but in order to use it you&#39;ll need to compile perl with macro definitions included in the debugging information. Using <i>gcc</i> version 3.1, this means configuring with <code>-Doptimize=-g3</code>. Other compilers might use a different switch (if they support debugging macros at all).</p>

<h2 id="Dumping-Perl-Data-Structures"><a class="permalink" href="perlhacktips.html#Dumping-Perl-Data-Structures">#</a><a id="Dumping"></a>Dumping Perl Data Structures</h2>

<p>One way to get around this macro hell is to use the dumping functions in <i>dump.c</i>; these work a little like an internal <a href="./Devel::Peek.html">Devel::Peek</a>, but they also cover OPs and other structures that you can&#39;t get at from Perl. Let&#39;s take an example. We&#39;ll use the <code>$a = $b + $c</code> we used before, but give it a bit of context: <code>$b = &quot;6XXXX&quot;; $c = 2.3;</code>. Where&#39;s a good place to stop and poke around?</p>

<p>What about <code>pp_add</code>, the function we examined earlier to implement the <code>+</code> operator:</p>

<pre><code class="plaintext">(gdb) break Perl_pp_add
Breakpoint 1 at 0x46249f: file pp_hot.c, line 309.</code></pre>

<p>Notice we use <code>Perl_pp_add</code> and not <code>pp_add</code> - see <a href="perlguts.html#Internal-Functions">&quot;Internal Functions&quot; in perlguts</a>. With the breakpoint in place, we can run our program:</p>

<pre><code>(gdb) run -e &#39;$b = &quot;6XXXX&quot;; $c = 2.3; $a = $b + $c&#39;</code></pre>

<p>Lots of junk will go past as gdb reads in the relevant source files and libraries, and then:</p>

<pre><code>Breakpoint 1, Perl_pp_add () at pp_hot.c:309
1396    dSP; dATARGET; bool useleft; SV *svl, *svr;
(gdb) step
311           dPOPTOPnnrl_ul;
(gdb)</code></pre>

<p>We looked at this bit of code before, and we said that <code>dPOPTOPnnrl_ul</code> arranges for two <code>NV</code>s to be placed into <code>left</code> and <code>right</code> - let&#39;s slightly expand it:</p>

<pre><code class="plaintext">#define dPOPTOPnnrl_ul  NV right = POPn; \
                        SV *leftsv = TOPs; \
                        NV left = USE_LEFT(leftsv) ? SvNV(leftsv) : 0.0</code></pre>

<p><code>POPn</code> takes the SV from the top of the stack and obtains its NV either directly (if <code>SvNOK</code> is set) or by calling the <code>sv_2nv</code> function. <code>TOPs</code> takes the next SV from the top of the stack - yes, <code>POPn</code> uses <code>TOPs</code> - but doesn&#39;t remove it. We then use <code>SvNV</code> to get the NV from <code>leftsv</code> in the same way as before - yes, <code>POPn</code> uses <code>SvNV</code>.</p>

<p>Since we don&#39;t have an NV for <code>$b</code>, we&#39;ll have to use <code>sv_2nv</code> to convert it. If we step again, we&#39;ll find ourselves there:</p>

<pre><code class="plaintext">(gdb) step
Perl_sv_2nv (sv=0xa0675d0) at sv.c:1669
1669        if (!sv)
(gdb)</code></pre>

<p>We can now use <code>Perl_sv_dump</code> to investigate the SV:</p>

<pre><code>(gdb) print Perl_sv_dump(sv)
SV = PV(0xa057cc0) at 0xa0675d0
REFCNT = 1
FLAGS = (POK,pPOK)
PV = 0xa06a510 &quot;6XXXX&quot;\0
CUR = 5
LEN = 6
$1 = void</code></pre>

<p>We know we&#39;re going to get <code>6</code> from this, so let&#39;s finish the subroutine:</p>

<pre><code>(gdb) finish
Run till exit from #0  Perl_sv_2nv (sv=0xa0675d0) at sv.c:1671
0x462669 in Perl_pp_add () at pp_hot.c:311
311           dPOPTOPnnrl_ul;</code></pre>

<p>We can also dump out this op: the current op is always stored in <code>PL_op</code>, and we can dump it with <code>Perl_op_dump</code>. This&#39;ll give us similar output to CPAN module B::Debug.</p>

<pre><code>(gdb) print Perl_op_dump(PL_op)
{
13  TYPE = add  ===&gt; 14
    TARG = 1
    FLAGS = (SCALAR,KIDS)
    {
        TYPE = null  ===&gt; (12)
          (was rv2sv)
        FLAGS = (SCALAR,KIDS)
        {
11          TYPE = gvsv  ===&gt; 12
            FLAGS = (SCALAR)
            GV = main::b
        }
    }</code></pre>

<p># finish this later #</p>

<h2 id="Using-gdb-to-look-at-specific-parts-of-a-program"><a class="permalink" href="perlhacktips.html#Using-gdb-to-look-at-specific-parts-of-a-program">#</a><a id="Using1"></a>Using gdb to look at specific parts of a program</h2>

<p>With the example above, you knew to look for <code>Perl_pp_add</code>, but what if there were multiple calls to it all over the place, or you didn&#39;t know what the op was you were looking for?</p>

<p>One way to do this is to inject a rare call somewhere near what you&#39;re looking for. For example, you could add <code>study</code> before your method:</p>

<pre><code>study;</code></pre>

<p>And in gdb do:</p>

<pre><code class="plaintext">(gdb) break Perl_pp_study</code></pre>

<p>And then step until you hit what you&#39;re looking for. This works well in a loop if you want to only break at certain iterations:</p>

<pre><code>for my $c (1..100) {
    study if $c == 50;
}</code></pre>

<h2 id="Using-gdb-to-look-at-what-the-parser/lexer-are-doing"><a class="permalink" href="perlhacktips.html#Using-gdb-to-look-at-what-the-parser/lexer-are-doing">#</a><a id="Using2"></a><a id="Using-gdb-to-look-at-what-the-parser-lexer-are-doing"></a>Using gdb to look at what the parser/lexer are doing</h2>

<p>If you want to see what perl is doing when parsing/lexing your code, you can use <code>BEGIN {}</code>:</p>

<pre><code>print &quot;Before\n&quot;;
BEGIN { study; }
print &quot;After\n&quot;;</code></pre>

<p>And in gdb:</p>

<pre><code class="plaintext">(gdb) break Perl_pp_study</code></pre>

<p>If you want to see what the parser/lexer is doing inside of <code>if</code> blocks and the like you need to be a little trickier:</p>

<pre><code>if ($a &amp;&amp; $b &amp;&amp; do { BEGIN { study } 1 } &amp;&amp; $c) { ... }</code></pre>

<h1 id="SOURCE-CODE-STATIC-ANALYSIS"><a class="permalink" href="perlhacktips.html#SOURCE-CODE-STATIC-ANALYSIS">#</a><a id="SOURCE"></a>SOURCE CODE STATIC ANALYSIS</h1>

<p>Various tools exist for analysing C source code <b>statically</b>, as opposed to <b>dynamically</b>, that is, without executing the code. It is possible to detect resource leaks, undefined behaviour, type mismatches, portability problems, code paths that would cause illegal memory accesses, and other similar problems by just parsing the C code and looking at the resulting graph, what does it tell about the execution and data flows. As a matter of fact, this is exactly how C compilers know to give warnings about dubious code.</p>

<h2 id="lint"><a class="permalink" href="perlhacktips.html#lint">#</a>lint</h2>

<p>The good old C code quality inspector, <code>lint</code>, is available in several platforms, but please be aware that there are several different implementations of it by different vendors, which means that the flags are not identical across different platforms.</p>

<p>There is a <code>lint</code> target in Makefile, but you may have to diddle with the flags (see above).</p>

<h2 id="Coverity"><a class="permalink" href="perlhacktips.html#Coverity">#</a>Coverity</h2>

<p>Coverity (<a href="http://www.coverity.com/">http://www.coverity.com/</a>) is a product similar to lint and as a testbed for their product they periodically check several open source projects, and they give out accounts to open source developers to the defect databases.</p>

<p>There is Coverity setup for the perl5 project: <a href="https://scan.coverity.com/projects/perl5">https://scan.coverity.com/projects/perl5</a></p>

<h2 id="HP-UX-cadvise-(Code-Advisor)"><a class="permalink" href="perlhacktips.html#HP-UX-cadvise-(Code-Advisor)">#</a><a id="HP"></a><a id="HP-UX-cadvise-Code-Advisor"></a>HP-UX cadvise (Code Advisor)</h2>

<p>HP has a C/C++ static analyzer product for HP-UX caller Code Advisor. (Link not given here because the URL is horribly long and seems horribly unstable; use the search engine of your choice to find it.) The use of the <code>cadvise_cc</code> recipe with <code>Configure ... -Dcc=./cadvise_cc</code> (see cadvise &quot;User Guide&quot;) is recommended; as is the use of <code>+wall</code>.</p>

<h2 id="cpd-(cut-and-paste-detector)"><a class="permalink" href="perlhacktips.html#cpd-(cut-and-paste-detector)">#</a><a id="cpd"></a><a id="cpd-cut-and-paste-detector"></a>cpd (cut-and-paste detector)</h2>

<p>The cpd tool detects cut-and-paste coding. If one instance of the cut-and-pasted code changes, all the other spots should probably be changed, too. Therefore such code should probably be turned into a subroutine or a macro.</p>

<p>cpd (<a href="http://pmd.sourceforge.net/cpd.html">http://pmd.sourceforge.net/cpd.html</a>) is part of the pmd project (<a href="http://pmd.sourceforge.net/">http://pmd.sourceforge.net/</a>). pmd was originally written for static analysis of Java code, but later the cpd part of it was extended to parse also C and C++.</p>

<p>Download the pmd-bin-X.Y.zip () from the SourceForge site, extract the pmd-X.Y.jar from it, and then run that on source code thusly:</p>

<pre><code class="plaintext">java -cp pmd-X.Y.jar net.sourceforge.pmd.cpd.CPD \
 --minimum-tokens 100 --files /some/where/src --language c &gt; cpd.txt</code></pre>

<p>You may run into memory limits, in which case you should use the -Xmx option:</p>

<pre><code class="plaintext">java -Xmx512M ...</code></pre>

<h2 id="gcc-warnings"><a class="permalink" href="perlhacktips.html#gcc-warnings">#</a><a id="gcc"></a>gcc warnings</h2>

<p>Though much can be written about the inconsistency and coverage problems of gcc warnings (like <code>-Wall</code> not meaning &quot;all the warnings&quot;, or some common portability problems not being covered by <code>-Wall</code>, or <code>-ansi</code> and <code>-pedantic</code> both being a poorly defined collection of warnings, and so forth), gcc is still a useful tool in keeping our coding nose clean.</p>

<p>The <code>-Wall</code> is by default on.</p>

<p>The <code>-ansi</code> (and its sidekick, <code>-pedantic</code>) would be nice to be on always, but unfortunately they are not safe on all platforms, they can for example cause fatal conflicts with the system headers (Solaris being a prime example). If Configure <code>-Dgccansipedantic</code> is used, the <code>cflags</code> frontend selects <code>-ansi -pedantic</code> for the platforms where they are known to be safe.</p>

<p>The following extra flags are added:</p>

<ul>

<li><p><code>-Wendif-labels</code></p>

</li>
<li><p><code>-Wextra</code></p>

</li>
<li><p><code>-Wc++-compat</code></p>

</li>
<li><p><code>-Wwrite-strings</code></p>

</li>
<li><p><code>-Werror=declaration-after-statement</code></p>

</li>
<li><p><code>-Werror=pointer-arith</code></p>

</li>
</ul>

<p>The following flags would be nice to have but they would first need their own Augean stablemaster:</p>

<ul>

<li><p><code>-Wshadow</code></p>

</li>
<li><p><code>-Wstrict-prototypes</code></p>

</li>
</ul>

<p>The <code>-Wtraditional</code> is another example of the annoying tendency of gcc to bundle a lot of warnings under one switch (it would be impossible to deploy in practice because it would complain a lot) but it does contain some warnings that would be beneficial to have available on their own, such as the warning about string constants inside macros containing the macro arguments: this behaved differently pre-ANSI than it does in ANSI, and some C compilers are still in transition, AIX being an example.</p>

<h2 id="Warnings-of-other-C-compilers"><a class="permalink" href="perlhacktips.html#Warnings-of-other-C-compilers">#</a><a id="Warnings"></a>Warnings of other C compilers</h2>

<p>Other C compilers (yes, there <b>are</b> other C compilers than gcc) often have their &quot;strict ANSI&quot; or &quot;strict ANSI with some portability extensions&quot; modes on, like for example the Sun Workshop has its <code>-Xa</code> mode on (though implicitly), or the DEC (these days, HP...) has its <code>-std1</code> mode on.</p>

<h1 id="MEMORY-DEBUGGERS"><a class="permalink" href="perlhacktips.html#MEMORY-DEBUGGERS">#</a><a id="MEMORY"></a>MEMORY DEBUGGERS</h1>

<p><b>NOTE 1</b>: Running under older memory debuggers such as Purify, valgrind or Third Degree greatly slows down the execution: seconds become minutes, minutes become hours. For example as of Perl 5.8.1, the ext/Encode/t/Unicode.t takes extraordinarily long to complete under e.g. Purify, Third Degree, and valgrind. Under valgrind it takes more than six hours, even on a snappy computer. The said test must be doing something that is quite unfriendly for memory debuggers. If you don&#39;t feel like waiting, that you can simply kill away the perl process. Roughly valgrind slows down execution by factor 10, AddressSanitizer by factor 2.</p>

<p><b>NOTE 2</b>: To minimize the number of memory leak false alarms (see <a href="perlhacktips.html#PERL_DESTRUCT_LEVEL">&quot;PERL_DESTRUCT_LEVEL&quot;</a> for more information), you have to set the environment variable PERL_DESTRUCT_LEVEL to 2. For example, like this:</p>

<pre><code class="plaintext">env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib ...</code></pre>

<p><b>NOTE 3</b>: There are known memory leaks when there are compile-time errors within eval or require, seeing <code>S_doeval</code> in the call stack is a good sign of these. Fixing these leaks is non-trivial, unfortunately, but they must be fixed eventually.</p>

<p><b>NOTE 4</b>: <a href="DynaLoader.html">DynaLoader</a> will not clean up after itself completely unless Perl is built with the Configure option <code>-Accflags=-DDL_UNLOAD_ALL_AT_EXIT</code>.</p>

<h2 id="valgrind"><a class="permalink" href="perlhacktips.html#valgrind">#</a>valgrind</h2>

<p>The valgrind tool can be used to find out both memory leaks and illegal heap memory accesses. As of version 3.3.0, Valgrind only supports Linux on x86, x86-64 and PowerPC and Darwin (OS X) on x86 and x86-64. The special &quot;test.valgrind&quot; target can be used to run the tests under valgrind. Found errors and memory leaks are logged in files named <i>testfile.valgrind</i> and by default output is displayed inline.</p>

<p>Example usage:</p>

<pre><code class="plaintext">make test.valgrind</code></pre>

<p>Since valgrind adds significant overhead, tests will take much longer to run. The valgrind tests support being run in parallel to help with this:</p>

<pre><code class="plaintext">TEST_JOBS=9 make test.valgrind</code></pre>

<p>Note that the above two invocations will be very verbose as reachable memory and leak-checking is enabled by default. If you want to just see pure errors, try:</p>

<pre><code class="plaintext">VG_OPTS=&#39;-q --leak-check=no --show-reachable=no&#39; TEST_JOBS=9 \
    make test.valgrind</code></pre>

<p>Valgrind also provides a cachegrind tool, invoked on perl as:</p>

<pre><code class="plaintext">VG_OPTS=--tool=cachegrind make test.valgrind</code></pre>

<p>As system libraries (most notably glibc) are also triggering errors, valgrind allows to suppress such errors using suppression files. The default suppression file that comes with valgrind already catches a lot of them. Some additional suppressions are defined in <i>t/perl.supp</i>.</p>

<p>To get valgrind and for more information see</p>

<pre><code class="plaintext">http://valgrind.org/</code></pre>

<h2 id="AddressSanitizer"><a class="permalink" href="perlhacktips.html#AddressSanitizer">#</a>AddressSanitizer</h2>

<p>AddressSanitizer (&quot;ASan&quot;) consists of a compiler instrumentation module and a run-time <code>malloc</code> library. ASan is available for a variety of architectures, operating systems, and compilers (see project link below). It checks for unsafe memory usage, such as use after free and buffer overflow conditions, and is fast enough that you can easily compile your debugging or optimized perl with it. Modern versions of ASan check for memory leaks by default on most platforms, otherwise (e.g. x86_64 OS X) this feature can be enabled via <code>ASAN_OPTIONS=detect_leaks=1</code>.</p>

<p>To build perl with AddressSanitizer, your Configure invocation should look like:</p>

<pre><code class="plaintext">sh Configure -des -Dcc=clang \
   -Accflags=-fsanitize=address -Aldflags=-fsanitize=address \
   -Alddlflags=-shared\ -fsanitize=address \
   -fsanitize-blacklist=`pwd`/asan_ignore</code></pre>

<p>where these arguments mean:</p>

<ul>

<li><p>-Dcc=clang</p>

<p>This should be replaced by the full path to your clang executable if it is not in your path.</p>

</li>
<li><p>-Accflags=-fsanitize=address</p>

<p>Compile perl and extensions sources with AddressSanitizer.</p>

</li>
<li><p>-Aldflags=-fsanitize=address</p>

<p>Link the perl executable with AddressSanitizer.</p>

</li>
<li><p>-Alddlflags=-shared\ -fsanitize=address</p>

<p>Link dynamic extensions with AddressSanitizer. You must manually specify <code>-shared</code> because using <code>-Alddlflags=-shared</code> will prevent Configure from setting a default value for <code>lddlflags</code>, which usually contains <code>-shared</code> (at least on Linux).</p>

</li>
<li><p>-fsanitize-blacklist=`pwd`/asan_ignore</p>

<p>AddressSanitizer will ignore functions listed in the <code>asan_ignore</code> file. (This file should contain a short explanation of why each of the functions is listed.)</p>

</li>
</ul>

<p>See also <a href="https://github.com/google/sanitizers/wiki/AddressSanitizer">https://github.com/google/sanitizers/wiki/AddressSanitizer</a>.</p>

<h1 id="PROFILING"><a class="permalink" href="perlhacktips.html#PROFILING">#</a>PROFILING</h1>

<p>Depending on your platform there are various ways of profiling Perl.</p>

<p>There are two commonly used techniques of profiling executables: <i>statistical time-sampling</i> and <i>basic-block counting</i>.</p>

<p>The first method takes periodically samples of the CPU program counter, and since the program counter can be correlated with the code generated for functions, we get a statistical view of in which functions the program is spending its time. The caveats are that very small/fast functions have lower probability of showing up in the profile, and that periodically interrupting the program (this is usually done rather frequently, in the scale of milliseconds) imposes an additional overhead that may skew the results. The first problem can be alleviated by running the code for longer (in general this is a good idea for profiling), the second problem is usually kept in guard by the profiling tools themselves.</p>

<p>The second method divides up the generated code into <i>basic blocks</i>. Basic blocks are sections of code that are entered only in the beginning and exited only at the end. For example, a conditional jump starts a basic block. Basic block profiling usually works by <i>instrumenting</i> the code by adding <i>enter basic block #nnnn</i> book-keeping code to the generated code. During the execution of the code the basic block counters are then updated appropriately. The caveat is that the added extra code can skew the results: again, the profiling tools usually try to factor their own effects out of the results.</p>

<h2 id="Gprof-Profiling"><a class="permalink" href="perlhacktips.html#Gprof-Profiling">#</a><a id="Gprof"></a>Gprof Profiling</h2>

<p><i>gprof</i> is a profiling tool available in many Unix platforms which uses <i>statistical time-sampling</i>. You can build a profiled version of <i>perl</i> by compiling using gcc with the flag <code>-pg</code>. Either edit <i>config.sh</i> or re-run <i>Configure</i>. Running the profiled version of Perl will create an output file called <i>gmon.out</i> which contains the profiling data collected during the execution.</p>

<p>quick hint:</p>

<pre><code class="plaintext">$ sh Configure -des -Dusedevel -Accflags=&#39;-pg&#39; \
    -Aldflags=&#39;-pg&#39; -Alddlflags=&#39;-pg -shared&#39; \
    &amp;&amp; make perl
$ ./perl ... # creates gmon.out in current directory
$ gprof ./perl &gt; out
$ less out</code></pre>

<p>(you probably need to add <code>-shared</code> to the &lt;-Alddlflags&gt; line until RT #118199 is resolved)</p>

<p>The <i>gprof</i> tool can then display the collected data in various ways. Usually <i>gprof</i> understands the following options:</p>

<ul>

<li><p>-a</p>

<p>Suppress statically defined functions from the profile.</p>

</li>
<li><p>-b</p>

<p>Suppress the verbose descriptions in the profile.</p>

</li>
<li><p>-e routine</p>

<p>Exclude the given routine and its descendants from the profile.</p>

</li>
<li><p>-f routine</p>

<p>Display only the given routine and its descendants in the profile.</p>

</li>
<li><p>-s</p>

<p>Generate a summary file called <i>gmon.sum</i> which then may be given to subsequent gprof runs to accumulate data over several runs.</p>

</li>
<li><p>-z</p>

<p>Display routines that have zero usage.</p>

</li>
</ul>

<p>For more detailed explanation of the available commands and output formats, see your own local documentation of <i>gprof</i>.</p>

<h2 id="GCC-gcov-Profiling"><a class="permalink" href="perlhacktips.html#GCC-gcov-Profiling">#</a><a id="GCC"></a>GCC gcov Profiling</h2>

<p><i>basic block profiling</i> is officially available in gcc 3.0 and later. You can build a profiled version of <i>perl</i> by compiling using gcc with the flags <code>-fprofile-arcs -ftest-coverage</code>. Either edit <i>config.sh</i> or re-run <i>Configure</i>.</p>

<p>quick hint:</p>

<pre><code class="plaintext">$ sh Configure -des -Dusedevel -Doptimize=&#39;-g&#39; \
    -Accflags=&#39;-fprofile-arcs -ftest-coverage&#39; \
    -Aldflags=&#39;-fprofile-arcs -ftest-coverage&#39; \
    -Alddlflags=&#39;-fprofile-arcs -ftest-coverage -shared&#39; \
    &amp;&amp; make perl
$ rm -f regexec.c.gcov regexec.gcda
$ ./perl ...
$ gcov regexec.c
$ less regexec.c.gcov</code></pre>

<p>(you probably need to add <code>-shared</code> to the &lt;-Alddlflags&gt; line until RT #118199 is resolved)</p>

<p>Running the profiled version of Perl will cause profile output to be generated. For each source file an accompanying <i>.gcda</i> file will be created.</p>

<p>To display the results you use the <i>gcov</i> utility (which should be installed if you have gcc 3.0 or newer installed). <i>gcov</i> is run on source code files, like this</p>

<pre><code class="plaintext">gcov sv.c</code></pre>

<p>which will cause <i>sv.c.gcov</i> to be created. The <i>.gcov</i> files contain the source code annotated with relative frequencies of execution indicated by &quot;#&quot; markers. If you want to generate <i>.gcov</i> files for all profiled object files, you can run something like this:</p>

<pre><code>for file in `find . -name \*.gcno`
do sh -c &quot;cd `dirname $file` &amp;&amp; gcov `basename $file .gcno`&quot;
done</code></pre>

<p>Useful options of <i>gcov</i> include <code>-b</code> which will summarise the basic block, branch, and function call coverage, and <code>-c</code> which instead of relative frequencies will use the actual counts. For more information on the use of <i>gcov</i> and basic block profiling with gcc, see the latest GNU CC manual. As of gcc 4.8, this is at <a href="http://gcc.gnu.org/onlinedocs/gcc/Gcov-Intro.html#Gcov-Intro">http://gcc.gnu.org/onlinedocs/gcc/Gcov-Intro.html#Gcov-Intro</a></p>

<h1 id="MISCELLANEOUS-TRICKS"><a class="permalink" href="perlhacktips.html#MISCELLANEOUS-TRICKS">#</a><a id="MISCELLANEOUS"></a>MISCELLANEOUS TRICKS</h1>

<h2 id="PERL_DESTRUCT_LEVEL"><a class="permalink" href="perlhacktips.html#PERL_DESTRUCT_LEVEL">#</a>PERL_DESTRUCT_LEVEL</h2>

<p>If you want to run any of the tests yourself manually using e.g. valgrind, please note that by default perl <b>does not</b> explicitly cleanup all the memory it has allocated (such as global memory arenas) but instead lets the exit() of the whole program &quot;take care&quot; of such allocations, also known as &quot;global destruction of objects&quot;.</p>

<p>There is a way to tell perl to do complete cleanup: set the environment variable PERL_DESTRUCT_LEVEL to a non-zero value. The t/TEST wrapper does set this to 2, and this is what you need to do too, if you don&#39;t want to see the &quot;global leaks&quot;: For example, for running under valgrind</p>

<pre><code class="plaintext">env PERL_DESTRUCT_LEVEL=2 valgrind ./perl -Ilib t/foo/bar.t</code></pre>

<p>(Note: the mod_perl apache module uses also this environment variable for its own purposes and extended its semantics. Refer to the mod_perl documentation for more information. Also, spawned threads do the equivalent of setting this variable to the value 1.)</p>

<p>If, at the end of a run you get the message <i>N scalars leaked</i>, you can recompile with <code>-DDEBUG_LEAKING_SCALARS</code>, (<code>Configure -Accflags=-DDEBUG_LEAKING_SCALARS</code>), which will cause the addresses of all those leaked SVs to be dumped along with details as to where each SV was originally allocated. This information is also displayed by Devel::Peek. Note that the extra details recorded with each SV increases memory usage, so it shouldn&#39;t be used in production environments. It also converts <code>new_SV()</code> from a macro into a real function, so you can use your favourite debugger to discover where those pesky SVs were allocated.</p>

<p>If you see that you&#39;re leaking memory at runtime, but neither valgrind nor <code>-DDEBUG_LEAKING_SCALARS</code> will find anything, you&#39;re probably leaking SVs that are still reachable and will be properly cleaned up during destruction of the interpreter. In such cases, using the <code>-Dm</code> switch can point you to the source of the leak. If the executable was built with <code>-DDEBUG_LEAKING_SCALARS</code>, <code>-Dm</code> will output SV allocations in addition to memory allocations. Each SV allocation has a distinct serial number that will be written on creation and destruction of the SV. So if you&#39;re executing the leaking code in a loop, you need to look for SVs that are created, but never destroyed between each cycle. If such an SV is found, set a conditional breakpoint within <code>new_SV()</code> and make it break only when <code>PL_sv_serial</code> is equal to the serial number of the leaking SV. Then you will catch the interpreter in exactly the state where the leaking SV is allocated, which is sufficient in many cases to find the source of the leak.</p>

<p>As <code>-Dm</code> is using the PerlIO layer for output, it will by itself allocate quite a bunch of SVs, which are hidden to avoid recursion. You can bypass the PerlIO layer if you use the SV logging provided by <code>-DPERL_MEM_LOG</code> instead.</p>

<h2 id="PERL_MEM_LOG"><a class="permalink" href="perlhacktips.html#PERL_MEM_LOG">#</a>PERL_MEM_LOG</h2>

<p>If compiled with <code>-DPERL_MEM_LOG</code> (<code>-Accflags=-DPERL_MEM_LOG</code>), both memory and SV allocations go through logging functions, which is handy for breakpoint setting.</p>

<p>Unless <code>-DPERL_MEM_LOG_NOIMPL</code> (<code>-Accflags=-DPERL_MEM_LOG_NOIMPL</code>) is also compiled, the logging functions read $ENV{PERL_MEM_LOG} to determine whether to log the event, and if so how:</p>

<pre><code>$ENV{PERL_MEM_LOG} =~ /m/           Log all memory ops
$ENV{PERL_MEM_LOG} =~ /s/           Log all SV ops
$ENV{PERL_MEM_LOG} =~ /t/           include timestamp in Log
$ENV{PERL_MEM_LOG} =~ /^(\d+)/      write to FD given (default is 2)</code></pre>

<p>Memory logging is somewhat similar to <code>-Dm</code> but is independent of <code>-DDEBUGGING</code>, and at a higher level; all uses of Newx(), Renew(), and Safefree() are logged with the caller&#39;s source code file and line number (and C function name, if supported by the C compiler). In contrast, <code>-Dm</code> is directly at the point of <code>malloc()</code>. SV logging is similar.</p>

<p>Since the logging doesn&#39;t use PerlIO, all SV allocations are logged and no extra SV allocations are introduced by enabling the logging. If compiled with <code>-DDEBUG_LEAKING_SCALARS</code>, the serial number for each SV allocation is also logged.</p>

<h2 id="DDD-over-gdb"><a class="permalink" href="perlhacktips.html#DDD-over-gdb">#</a><a id="DDD"></a>DDD over gdb</h2>

<p>Those debugging perl with the DDD frontend over gdb may find the following useful:</p>

<p>You can extend the data conversion shortcuts menu, so for example you can display an SV&#39;s IV value with one click, without doing any typing. To do that simply edit ~/.ddd/init file and add after:</p>

<pre><code class="plaintext">! Display shortcuts.
Ddd*gdbDisplayShortcuts: \
/t ()   // Convert to Bin\n\
/d ()   // Convert to Dec\n\
/x ()   // Convert to Hex\n\
/o ()   // Convert to Oct(\n\</code></pre>

<p>the following two lines:</p>

<pre><code>((XPV*) (())-&gt;sv_any )-&gt;xpv_pv  // 2pvx\n\
((XPVIV*) (())-&gt;sv_any )-&gt;xiv_iv // 2ivx</code></pre>

<p>so now you can do ivx and pvx lookups or you can plug there the sv_peek &quot;conversion&quot;:</p>

<pre><code class="plaintext">Perl_sv_peek(my_perl, (SV*)()) // sv_peek</code></pre>

<p>(The my_perl is for threaded builds.) Just remember that every line, but the last one, should end with \n\</p>

<p>Alternatively edit the init file interactively via: 3rd mouse button -&gt; New Display -&gt; Edit Menu</p>

<p>Note: you can define up to 20 conversion shortcuts in the gdb section.</p>

<h2 id="C-backtrace"><a class="permalink" href="perlhacktips.html#C-backtrace">#</a><a id="C"></a>C backtrace</h2>

<p>On some platforms Perl supports retrieving the C level backtrace (similar to what symbolic debuggers like gdb do).</p>

<p>The backtrace returns the stack trace of the C call frames, with the symbol names (function names), the object names (like &quot;perl&quot;), and if it can, also the source code locations (file:line).</p>

<p>The supported platforms are Linux, and OS X (some *BSD might work at least partly, but they have not yet been tested).</p>

<p>This feature hasn&#39;t been tested with multiple threads, but it will only show the backtrace of the thread doing the backtracing.</p>

<p>The feature needs to be enabled with <code>Configure -Dusecbacktrace</code>.</p>

<p>The <code>-Dusecbacktrace</code> also enables keeping the debug information when compiling/linking (often: <code>-g</code>). Many compilers/linkers do support having both optimization and keeping the debug information. The debug information is needed for the symbol names and the source locations.</p>

<p>Static functions might not be visible for the backtrace.</p>

<p>Source code locations, even if available, can often be missing or misleading if the compiler has e.g. inlined code. Optimizer can make matching the source code and the object code quite challenging.</p>

<dl>

<dt id="Linux"><a class="permalink" href="perlhacktips.html#Linux">#</a>Linux</dt>
<dd>

<p>You <b>must</b> have the BFD (-lbfd) library installed, otherwise <code>perl</code> will fail to link. The BFD is usually distributed as part of the GNU binutils.</p>

<p>Summary: <code>Configure ... -Dusecbacktrace</code> and you need <code>-lbfd</code>.</p>

</dd>
<dt id="OS-X"><a class="permalink" href="perlhacktips.html#OS-X">#</a><a id="OS"></a>OS X</dt>
<dd>

<p>The source code locations are supported <b>only</b> if you have the Developer Tools installed. (BFD is <b>not</b> needed.)</p>

<p>Summary: <code>Configure ... -Dusecbacktrace</code> and installing the Developer Tools would be good.</p>

</dd>
</dl>

<p>Optionally, for trying out the feature, you may want to enable automatic dumping of the backtrace just before a warning or croak (die) message is emitted, by adding <code>-Accflags=-DUSE_C_BACKTRACE_ON_ERROR</code> for Configure.</p>

<p>Unless the above additional feature is enabled, nothing about the backtrace functionality is visible, except for the Perl/XS level.</p>

<p>Furthermore, even if you have enabled this feature to be compiled, you need to enable it in runtime with an environment variable: <code>PERL_C_BACKTRACE_ON_ERROR=10</code>. It must be an integer higher than zero, telling the desired frame count.</p>

<p>Retrieving the backtrace from Perl level (using for example an XS extension) would be much less exciting than one would hope: normally you would see <code>runops</code>, <code>entersub</code>, and not much else. This API is intended to be called <b>from within</b> the Perl implementation, not from Perl level execution.</p>

<p>The C API for the backtrace is as follows:</p>

<dl>

<dt id="get_c_backtrace"><a class="permalink" href="perlhacktips.html#get_c_backtrace">#</a>get_c_backtrace</dt>
<dd>

</dd>
<dt id="free_c_backtrace"><a class="permalink" href="perlhacktips.html#free_c_backtrace">#</a>free_c_backtrace</dt>
<dd>

</dd>
<dt id="get_c_backtrace_dump"><a class="permalink" href="perlhacktips.html#get_c_backtrace_dump">#</a>get_c_backtrace_dump</dt>
<dd>

</dd>
<dt id="dump_c_backtrace"><a class="permalink" href="perlhacktips.html#dump_c_backtrace">#</a>dump_c_backtrace</dt>
<dd>

</dd>
</dl>

<h2 id="Poison"><a class="permalink" href="perlhacktips.html#Poison">#</a>Poison</h2>

<p>If you see in a debugger a memory area mysteriously full of 0xABABABAB or 0xEFEFEFEF, you may be seeing the effect of the Poison() macros, see <a href="perlclib.html">perlclib</a>.</p>

<h2 id="Read-only-optrees"><a class="permalink" href="perlhacktips.html#Read-only-optrees">#</a><a id="Read"></a>Read-only optrees</h2>

<p>Under ithreads the optree is read only. If you want to enforce this, to check for write accesses from buggy code, compile with <code>-Accflags=-DPERL_DEBUG_READONLY_OPS</code> to enable code that allocates op memory via <code>mmap</code>, and sets it read-only when it is attached to a subroutine. Any write access to an op results in a <code>SIGBUS</code> and abort.</p>

<p>This code is intended for development only, and may not be portable even to all Unix variants. Also, it is an 80% solution, in that it isn&#39;t able to make all ops read only. Specifically it does not apply to op slabs belonging to <code>BEGIN</code> blocks.</p>

<p>However, as an 80% solution it is still effective, as it has caught bugs in the past.</p>

<h2 id="When-is-a-bool-not-a-bool?"><a class="permalink" href="perlhacktips.html#When-is-a-bool-not-a-bool?">#</a><a id="When"></a><a id="When-is-a-bool-not-a-bool"></a>When is a bool not a bool?</h2>

<p>On pre-C99 compilers, <code>bool</code> is defined as equivalent to <code>char</code>. Consequently assignment of any larger type to a <code>bool</code> is unsafe and may be truncated. The <code>cBOOL</code> macro exists to cast it correctly; you may also find that using it is shorter and clearer than writing out the equivalent conditional expression longhand.</p>

<p>On those platforms and compilers where <code>bool</code> really is a boolean (C++, C99), it is easy to forget the cast. You can force <code>bool</code> to be a <code>char</code> by compiling with <code>-Accflags=-DPERL_BOOL_AS_CHAR</code>. You may also wish to run <code>Configure</code> with something like</p>

<pre><code class="plaintext">-Accflags=&#39;-Wconversion -Wno-sign-conversion -Wno-shorten-64-to-32&#39;</code></pre>

<p>or your compiler&#39;s equivalent to make it easier to spot any unsafe truncations that show up.</p>

<p>The <code>TRUE</code> and <code>FALSE</code> macros are available for situations where using them would clarify intent. (But they always just mean the same as the integers 1 and 0 regardless, so using them isn&#39;t compulsory.)</p>

<h2 id="The-.i-Targets"><a class="permalink" href="perlhacktips.html#The-.i-Targets">#</a><a id="The"></a>The .i Targets</h2>

<p>You can expand the macros in a <i>foo.c</i> file by saying</p>

<pre><code class="plaintext">make foo.i</code></pre>

<p>which will expand the macros using cpp. Don&#39;t be scared by the results.</p>

<h1 id="AUTHOR"><a class="permalink" href="perlhacktips.html#AUTHOR">#</a>AUTHOR</h1>

<p>This document was originally written by Nathan Torkington, and is maintained by the perl5-porters mailing list.</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
